import React, { useEffect, useState } from 'react';
import {
  Button,
  DatePicker,
  message,
  Space,
  Table,
  Tag,
  TreeSelect,
  Tooltip,
} from 'antd';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getAllUser, getAllDepartment, delUser } from '@/api/user/user-manager';
import UserAdd from './components/userAdd';
import Userchange from './components/userChange';
import UserDetail from './components/userDetail';

import './index.less';

const { RangePicker } = DatePicker;

export type TableListItem = {
  userId: number;
  username: string | number;
  ssex: string;
  callNumber: number;
  creator: string;
  deptName: string;
  status: string;
  createTime: number;
  memo: string;
};

const columns: ProColumns<TableListItem>[] = [
  {
    title: '用户名',
    width: 120,
    dataIndex: 'username',
    copyable: true, //是否支持复制
    fixed: 'left', //固定左边
  },
  {
    title: '性别',
    width: 80,
    dataIndex: 'ssex',
    hideInSearch: true,
    // search: false,
    filters: true,
    onFilter: true, //启用本地筛选
    valueEnum: {
      ['0']: { text: '女' },
      ['1']: { text: '男' },
      ['2']: { text: '保密' },
    },
  },
  {
    title: '邮箱',
    hideInSearch: true,
    width: 150,
    dataIndex: 'email',
    // fixed: 'left',
  },
  {
    title: '部门',
    width: 120,
    dataIndex: 'deptName',
    valueType: 'select',
    request: async (): Promise<any> => {
      return await getAllDepartment();
    },
    renderFormItem: (a, b: any, c) => {
      // console.log(b.options ? b.options : b);
      let ele = (
        <TreeSelect
          // value={this.state.value}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          treeData={b.options ? b.options.data.rows.children : []}
          placeholder="请选择"
          treeDefaultExpandAll
        />
      );
      return ele;
    },
  },
  {
    width: 100,
    title: '电话',
    hideInSearch: true,
    dataIndex: 'mobile',
  },
  {
    title: '状态',
    hideInSearch: true,
    width: 80,
    dataIndex: 'status',
    render: (_, record) => {
      let color;
      record.status === '1' ? (color = 'green') : (color = 'red');
      return (
        <Space>
          <Tag color={color}>{record.status === '1' ? '有效' : '锁定'}</Tag>
        </Space>
      );
    },
  },
  {
    title: '创建时间',
    width: 140,
    // key: 'since',
    dataIndex: 'createTime',
    valueType: 'date',
    sorter: (a, b) => a.createTime - b.createTime,
    renderFormItem: () => {
      return <RangePicker />;
    },
  },

  {
    title: '操作',
    width: 80,
    key: 'option',
    valueType: 'option',
    fixed: 'right',
    render: (_, b, c, action: any) => {
      return (
        <>
          <Userchange data={b} refresh={action.reload}></Userchange>
          <UserDetail userData={b}></UserDetail>
        </>
      );
    },
  },
];

export default () => {
  // 获取基础列表
  const [userData, setUserData] = useState([]);

  const getData = () => {
    getAllUser().then(({ data }) => {
      setUserData(data.rows);
      // console.log(data.rows);
    });
  };

  let handleTool = (
    <>
      <UserAdd add={getData}></UserAdd>
      <Button key="show2">更多操作</Button>
    </>
  );

  return (
    <ProTable<TableListItem>
      // params={params}
      request={async (
        // 第一个参数 params 查询表单和 params 参数的结合
        // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
        params,
        sort,
        filter,
      ) => {
        // console.log(params);
        // console.log(sort, filter);

        let searchData = {
          pageNum: params.current,
          pageSize: params.pageSize,
          createTimeFrom: params.createTime ? params.createTime[0] : '',
          createTimeTo: params.createTime ? params.createTime[1] : '',
          deptId: params.deptName,
          ...params,
        };
        console.log(searchData);

        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        const { data } = await getAllUser(searchData);
        setUserData(data.rows);
        // console.log(data);

        return {
          data: data.rows,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: true,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: data.total,
        };
      }}
      columns={columns}
      rowSelection={{
        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
        // 注释该行则默认不显示下拉选项
        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      }}
      tableAlertRender={({
        selectedRowKeys,
        selectedRows,
        onCleanSelected,
      }) => (
        <Space size={24}>
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        </Space>
      )}
      tableAlertOptionRender={({ selectedRowKeys }) => {
        const del = () => {
          selectedRowKeys.forEach((v) => {
            delUser(`${v}`).then((res) => {
              message.success('删除成功');
              getData();
              // console.log(res);
            });
          });
        };
        return (
          <Button onClick={del}>批量删除</Button>
          // <Space size={16}>

          //   <a>导出数据</a>
          // </Space>
        );
      }}
      dataSource={userData}
      scroll={{ x: 1300 }}
      options={false}
      search={{
        labelWidth: 'auto',
        className: 'delMargin',
      }}
      rowKey="userId"
      headerTitle={handleTool}
      pagination={{
        pageSize: 10,
      }}
      // toolBarRender={() => [<Button key="show">查看日志</Button>]}
    />
  );
};
